package com.chen.expection.config;

import com.chen.expection.expection.ServiceExpection;
import com.chen.pojo.CommonResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


import javax.validation.ConstraintViolationException;

import static com.chen.expection.constant.ErrorCodeConstant.VALIDATIONERRORCODE;

@RestControllerAdvice
public class GolbalExpectionHandler {
    /**
     * 对serviceExpection的处理
     * @param ex
     * @return
     */
    @ExceptionHandler(ServiceExpection.class)
    public CommonResult serviceExpectionHandler(ServiceExpection ex){
        CommonResult commonResult = new CommonResult();
        commonResult.setData(null);
        commonResult.setMsg(ex.getMessage());
        commonResult.setCode(ex.getCode());
        return commonResult;
    }
    /**
     * 对检验时候抛出异常的处理
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class})
    public CommonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex){
        CommonResult commonResult = new CommonResult();
        commonResult.setData(null);
        commonResult.setMsg(ex.getMessage());
        commonResult.setCode(VALIDATIONERRORCODE);
        return commonResult;
    }
}
